package com.zeeephr.core.sax;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.zeeephr.core.bean.Conf;

public class ConfHandler extends DefaultHandler {

	
	
	Conf conf;
	String tag;
	
	public Conf getConf() {
		return conf;
	}

	@Override
	public void startDocument() throws SAXException {
		System.out.println("开始解析conf.xml");
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		tag=qName;
		if("server-conf".equals(qName)) conf=new Conf();
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		String str=new String(ch,start,length).trim();
		if(str.length()>0) {
			switch(tag) {
			case "server-name":
				conf.setName(str);
				break;
			case "server-port":
				try {
					conf.setPort(Integer.parseInt(str));
				}catch (Exception e) {
					System.out.println("server-port 中输入的不是数字");// TODO: handle exception
				}
				break;
			case "size":
				try{conf.setSize(Integer.parseInt(str));
				
				}catch (Exception e) {
					System.out.println("size 中输入的不是数字");// TODO: handle exception
				}
				
				break;
			
			
			}
		}
	}

	@Override
	public void endDocument() throws SAXException {
		System.out.println("解析结束");
		if(conf==null) {
			throw new RuntimeException("未解析到conf");
		}
		if(conf.getSize()==0) {
			conf=null;
			throw new RuntimeException("设置的空间大小不能为0");
		}
		int port=conf.getPort();
		if(port<1025&&port>=0) {
			conf=null;
			throw new RuntimeException("设置的端口区间不能为0~1024");
		}
		System.out.println(conf);
	}
	
	
}
